﻿using MediatR;
using Medical.Api.Write.Application.Command.PackagingSterilization.SterilizationRegistration;
using Medical.Domain.PackagingSterilization;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.Extensions.Logging;

namespace Medical.Api.Write.Application.Handler.PackagingSterilization.Sterilization
{
    /// <summary>
    /// 修改灭菌状态的命令处理
    /// </summary>
    public class UpdateSterilizationStateCommandHandlter : IRequestHandler<UpdateSterilizationStateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SterilizationRegistration> _sterilizationRegistrationRepository;
        private readonly ILogger<UpdateSterilizationStateCommandHandlter> _logger;

        public UpdateSterilizationStateCommandHandlter(
            IBaseRepository<SterilizationRegistration> sterilizationRegistrationRepository,
            ILogger<UpdateSterilizationStateCommandHandlter> logger)
        {
            _sterilizationRegistrationRepository = sterilizationRegistrationRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateSterilizationStateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理灭菌状态更新，ID：{Id}，新状态：{State}", request.Id, request.State);
                var existingSterilization = await _sterilizationRegistrationRepository.GetModelAsync(request.Id);
                if (existingSterilization == null)
                {
                    _logger.LogWarning("未找到ID为{Id}的灭菌登记记录", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.Id}的灭菌登记记录"
                    };
                }
                if (existingSterilization.IsDeleted)
                {
                    _logger.LogWarning("ID为{Id}的灭菌登记记录已被删除", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"ID为{request.Id}的灭菌登记记录已被删除"
                    };
                }
                existingSterilization.Status = request.State;
                existingSterilization.UpdateTime = DateTime.Now;
                if (request.State == 1)
                {
                    existingSterilization.CompletionTime = DateTime.Now;
                }
                var updateResult = _sterilizationRegistrationRepository.Update(existingSterilization);
                if (updateResult > 0)
                {
                    _logger.LogInformation("成功更新灭菌状态，ID：{Id}，新状态：{State}", request.Id, request.State);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Success,
                        Data = request.Id,
                        Msg = "成功更新灭菌状态"
                    };
                }
                else
                {
                    _logger.LogWarning("更新灭菌状态失败，ID：{Id}，新状态：{State}", request.Id, request.State);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = "更新灭菌状态失败"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新灭菌状态时发生异常，ID：{Id}，新状态：{State}", request.Id, request.State);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Data = 0,
                    Msg = $"更新灭菌状态异常：{ex.Message}"
                };
            }
        }
    }
}
